import {observable, action, /*runInAction*/} from 'mobx'
import {StoreBase} from "@/stores";
import {ValidatorBase} from '@/components/Validation/Validator'

/**
 * 表单字段
 */
export class FormFieldStore extends StoreBase {

    constructor(props) {
        super(props)

        if (props) {
            const {name, validations, disabled, value} = props
            this.name = name
            this.validations = validations
            this.disabled = disabled
            this.value = value
        }
    }

    /**
     * 字段名称
     */
    @observable name
    /**
     * 值
     */
    @observable value
    /**
     * 是否禁用
     * @type {boolean}
     */
    @observable disabled = false
    /**
     * 是否可选择
     * @type {boolean}
     */
    @observable checkable = false
    /**
     * 是否验证无效
     * @type {boolean}
     */
    @observable invalid = false
    /**
     * 是否已验证过(不论成功或失败)
     * @type {boolean}
     */
    @observable validated = false
    /**
     * 验证错误信息
     * @type {Array}
     */
    @observable errors = []
    /**
     * 验证器
     * @type {Array}
     */
    @observable validations = []

    /**
     * 执行验证
     */
    @action
    async validate() {
        if (!this.validations || this.validations.length === 0) {
            return
        }
        for (let index = 0; index < this.validations.length; index++) {
            this.parent.validatingIncrease()	//正在验证项+1
            const validation = this.validations[index]
            let validationResult = undefined
            const params = {
                value: this.value,
                children: this.parent.children
            }
            if (validation instanceof ValidatorBase) {
                validationResult = validation.validate(params)
            } else {
                validationResult = validation().validate(params)
            }
            if (validationResult && validationResult instanceof Promise) { //如果返回的异步对象
                const temp = await validationResult()
                if (!this.validateResult(temp)) {
                    break
                }
            } else {
                if (!this.validateResult(validationResult)) {
                    break
                }
            }
        }
    }

    /**
     *
     * @param result
     * @returns {boolean} 是否验证通过
     */

    @action validateResult(result) {
        let isSuccessed = false
        //清理错误
        this.errors = []
        this.validated = true
        if (result) {//表示验证未通过
            this.errors.push(result)
            this.invalid = true
            this.parent.errorIncrease()//错误项目+1
        } else {
            this.invalid = false
            isSuccessed = true
            this.parent.errorDecrease()//错误项目-1
        }
        this.parent.validatingDecrease()  //正在验证项-1
        return isSuccessed
    }


    @action changeValue(value) {
        this.value = value
    }
}

